#!/bin/bash
# 同时启动前端和后端服务 - 后台运行版本

echo "=========================================="
echo "   CMDB - 启动所有服务"
echo "=========================================="
echo ""

# 获取脚本所在目录
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$SCRIPT_DIR"

# 创建日志目录
mkdir -p logs
rm -rf logs/backend.log 2>/dev/null
rm -rf logs/frontend.log 2>/dev/null
touch logs/backend.log
touch logs/frontend.log

# 激活虚拟环境
if [ ! -d ".venv" ]; then
    echo "❌ 虚拟环境不存在，请先运行: bash deploy.sh"
    exit 1
fi

. .venv/bin/activate

# 启动后端
echo "🚀 启动后端服务..."
cd backend
nohup daphne -b 0.0.0.0 -p 8000 backend.asgi:application > ../logs/backend.log 2>&1 &
BACKEND_PID=$!
echo $BACKEND_PID > ../logs/backend.pid
cd ..
echo "  后端 PID: $BACKEND_PID"

# 等待后端启动
echo "⏳ 等待后端启动..."
sleep 2
for i in {1..10}; do
    if curl -s http://localhost:8000/admin/ > /dev/null 2>&1; then
        echo "  ✅ 后端已启动"
        break
    fi
    sleep 1
    echo -n "."
done
echo ""

# 启动前端
echo "🚀 启动前端服务..."
cd frontend
nohup npm run dev > ../logs/frontend.log 2>&1 &
FRONTEND_PID=$!
echo $FRONTEND_PID > ../logs/frontend.pid
cd ..
echo "  前端 PID: $FRONTEND_PID"

# 等待前端启动
echo "⏳ 等待前端启动..."
sleep 3
for i in {1..15}; do
    if curl -s http://localhost:8080 > /dev/null 2>&1; then
        echo "  ✅ 前端已启动"
        break
    fi
    sleep 1
    echo -n "."
done
echo ""

echo "=========================================="
echo "   ✅ 所有服务已启动"
echo "=========================================="
echo ""
echo "📊 服务信息:"
echo "  前端: http://localhost:8080 (PID: $FRONTEND_PID)"
echo "  后端: http://localhost:8000 (PID: $BACKEND_PID)"
echo "  Admin: http://localhost:8000/admin/"
echo ""
echo "📝 管理命令:"
echo "  bash logs.sh follow  - 实时查看日志"
echo "  bash status.sh       - 查看服务状态"
echo "  bash stop.sh         - 停止所有服务"
echo ""
echo "📂 日志文件:"
echo "  后端: logs/backend.log"
echo "  前端: logs/frontend.log"
echo ""
